<template>
  <div class="relative">
    <ToolbarButton
      type="popover"
      icon="i-ri-table-fill"
      title="背景颜色"
      :active="isActive"
      popover-placement="bottom-start"
      :popover-width="240"
      popover-trigger="click"
      :large-icon="largeIcon"
      :hide-text="hideText"
      :disabled="!canSetCellBackground"
      @popover-hide="handlePopoverHide"
      @popover-after-leave="handlePopoverHide"
    >
      <template #popover>
        <div class="color-picker-panel">
          <!-- 默认颜色区域 -->
          <div class="default-colors-section">
            <button class="default-color-button" @click="setColor('#ffffff')">
              默认颜色
            </button>
          </div>

          <!-- 推荐颜色区域 -->
          <div class="recommended-colors-section">
            <div class="section-title">推荐颜色</div>
            <div class="recommended-colors-grid">
              <div
                v-for="color in recommendedColors"
                :key="color"
                :style="{ backgroundColor: color }"
                :class="[
                  'color-item',
                  pendingColor === color ? 'color-item-active' : '',
                ]"
                :title="color"
                @click="setColor(color)"
              />
            </div>
          </div>

          <!-- 标准色区域 -->
          <div class="standard-colors-section">
            <div class="section-title">标准色</div>
            <div class="standard-colors-grid">
              <div
                v-for="color in standardColors"
                :key="color"
                :style="{ backgroundColor: color }"
                :class="[
                  'color-item',
                  pendingColor === color ? 'color-item-active' : '',
                ]"
                :title="color"
                @click="setColor(color)"
              />
            </div>
          </div>

          <!-- 更多颜色区域 -->
          <div class="more-colors-section">
            <div
              class="more-colors-button"
              @click="showColorPicker = !showColorPicker"
            >
              <div class="more-colors-icon">
                <div class="rainbow-circle"></div>
              </div>
              <span>更多颜色</span>
            </div>

            <!-- 调色板区域 -->
            <div v-if="showColorPicker" class="color-picker-section">
              <ColorPickerPanel
                :model-value="tempColor"
                show-alpha
                @update:model-value="handleColorChange"
              />
            </div>
          </div>

          <!-- 最近使用的颜色 -->
          <div v-if="recentColors.length > 0" class="recent-colors-section">
            <div class="section-title">最近使用</div>
            <div class="recent-colors-grid">
              <div
                v-for="color in recentColors"
                :key="color"
                :style="{ backgroundColor: color }"
                class="color-item"
                :title="color"
                @click="setColor(color)"
              />
            </div>
          </div>

          <!-- 操作按钮区域 -->
          <div class="action-buttons">
            <button
              class="action-button action-button-text"
              @click="clearColor"
            >
              清除颜色
            </button>
            <button
              class="action-button action-button-primary"
              @click="confirmColor"
            >
              确定
            </button>
          </div>
        </div>
      </template>
    </ToolbarButton>
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  inject,
  ref,
  watch,
  nextTick,
  onBeforeUnmount,
  type Ref,
} from "vue";
import type { Editor } from "@tiptap/vue-3";
import type { EditorProps } from "../../../../types";
import ToolbarButton from "../../../button/index.vue";
import { defaultDicts } from "../../../../config/constants";
import { ColorPickerPanel } from "../../../color-picker";

defineOptions({
  name: "CellBackgroundColor",
});

const props = withDefaults(
  defineProps<{
    largeIcon?: boolean;
    hideText?: boolean;
  }>(),
  {
    largeIcon: false,
    hideText: true,
  }
);

// 注入编辑器实例和配置
const editor = inject<Ref<Editor>>("editor");
const editorProps = inject<EditorProps>("editorProps");

// 状态管理
const currentColor = ref("#ffffff");
const tempColor = ref("#ffffff");
const pendingColor = ref<string | null>(null); // 待确认的颜色
const recentColors = ref<string[]>([]);
const showColorPicker = ref(false);

// 颜色选项 - 从 EditorProps.dicts.colors 获取，如果没有则使用默认值
const recommendedColors = computed(() => {
  return editorProps?.dicts?.colors || defaultDicts.colors || [];
});

// 标准色 - 从 EditorProps.dicts.standardColors 获取，如果没有则使用默认值
const standardColors = computed(() => {
  return (
    editorProps?.dicts?.standardColors || defaultDicts.standardColors || []
  );
});

const isActive = computed(() => {
  if (!editor?.value) return false;
  return (
    editor.value.isActive("tableCell") || editor.value.isActive("tableHeader")
  );
});

const canSetCellBackground = computed(() => {
  if (!editor?.value) return false;
  return (
    editor.value.isActive("tableCell") || editor.value.isActive("tableHeader")
  );
});

// 获取当前单元格背景颜色
const getCurrentColor = () => {
  if (!editor?.value) return "#ffffff";
  // 优先检查 tableCell，如果不在 tableCell 中则检查 tableHeader
  if (editor.value.isActive("tableCell")) {
    const attrs = editor.value.getAttributes("tableCell");
    return attrs?.background || "#ffffff";
  }
  if (editor.value.isActive("tableHeader")) {
    const attrs = editor.value.getAttributes("tableHeader");
    return attrs?.background || "#ffffff";
  }
  return "#ffffff";
};

// 更新当前颜色
const updateCurrentColor = () => {
  const color = getCurrentColor();
  currentColor.value = color;
  tempColor.value = color;
  // 如果还没有待确认的颜色，也更新待确认颜色
  if (pendingColor.value === null) {
    pendingColor.value = color;
  }
};

// 监听编辑器变化
watch(
  () => editor?.value,
  (newEditor, oldEditor) => {
    // 清理旧编辑器的监听器
    if (oldEditor) {
      oldEditor.off("selectionUpdate", updateCurrentColor);
      oldEditor.off("transaction", updateCurrentColor);
    }

    if (newEditor) {
      newEditor.on("selectionUpdate", updateCurrentColor);
      newEditor.on("transaction", updateCurrentColor);
      updateCurrentColor();
    }
  },
  { immediate: true }
);

// 组件卸载时清理事件监听器
onBeforeUnmount(() => {
  if (editor?.value && updateCurrentColor) {
    editor.value.off("selectionUpdate", updateCurrentColor);
    editor.value.off("transaction", updateCurrentColor);
  }
});

const setColor = (color: string) => {
  // 验证颜色格式
  if (!isValidColor(color)) {
    return;
  }

  // 只更新待确认的颜色，不立即应用
  pendingColor.value = color;
  tempColor.value = color;
};

const handleColorChange = (color: string | null) => {
  if (color) {
    setColor(color);
  }
};

// 确认应用颜色
const confirmColor = () => {
  if (!pendingColor.value) return;

  const color = pendingColor.value;

  // 验证颜色格式
  if (!isValidColor(color)) {
    return;
  }

  // 更新当前颜色
  currentColor.value = color;

  // 添加到最近使用的颜色
  addToRecentColors(color);

  if (!editor?.value) {
    return;
  }

  // 应用背景颜色到单元格
  editor.value.chain().focus().setCellAttribute("background", color).run();

  // 关闭弹窗
  closePopover();
};

// 处理弹窗关闭事件
const handlePopoverHide = () => {
  // 重置所有展开状态
  showColorPicker.value = false;
};

// 关闭弹窗
const closePopover = () => {
  nextTick(() => {
    // 通过触发点击外部区域来关闭所有打开的 popover
    const tempDiv = document.createElement("div");
    tempDiv.style.position = "fixed";
    tempDiv.style.top = "0";
    tempDiv.style.left = "0";
    tempDiv.style.width = "1px";
    tempDiv.style.height = "1px";
    tempDiv.style.opacity = "0";
    tempDiv.style.pointerEvents = "auto";
    document.body.appendChild(tempDiv);
    tempDiv.click();
    setTimeout(() => {
      document.body.removeChild(tempDiv);
    }, 10);
  });
};

const clearColor = () => {
  if (!editor?.value) return;

  editor.value.chain().focus().setCellAttribute("background", null).run();

  currentColor.value = "#ffffff";
  tempColor.value = "#ffffff";
  pendingColor.value = "#ffffff";
};

// 添加到最近使用的颜色
const addToRecentColors = (color: string) => {
  const index = recentColors.value.indexOf(color);
  if (index > -1) {
    recentColors.value.splice(index, 1);
  }
  recentColors.value.unshift(color);

  // 限制最近使用的颜色数量
  if (recentColors.value.length > 8) {
    recentColors.value = recentColors.value.slice(0, 8);
  }

  // 保存到本地存储
  localStorage.setItem(
    "recent-cell-background-colors",
    JSON.stringify(recentColors.value)
  );
};

// 从本地存储加载最近使用的颜色
const loadRecentColors = () => {
  try {
    const saved = localStorage.getItem("recent-cell-background-colors");
    if (saved) {
      recentColors.value = JSON.parse(saved);
    }
  } catch (error) {
    console.warn("Failed to load recent cell background colors:", error);
  }
};

// 验证颜色格式
const isValidColor = (color: string): boolean => {
  if (!color) return false;

  // 检查十六进制颜色格式
  const hexPattern = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
  // 检查 rgba 格式
  const rgbaPattern = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)$/;
  // 检查 rgb 格式
  const rgbPattern = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/;

  return (
    hexPattern.test(color) || rgbaPattern.test(color) || rgbPattern.test(color)
  );
};

// 初始化
loadRecentColors();
</script>

<style scoped>
.section-title {
  font-size: 12px;
  color: #606266;
  margin-bottom: 6px;
  font-weight: 500;
}

.default-colors-section,
.recommended-colors-section,
.standard-colors-section {
  margin-bottom: 8px;
}

.recommended-colors-grid {
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  gap: 1px;
}

.standard-colors-grid {
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  gap: 1px;
}

.color-item {
  width: 16px;
  height: 16px;
  border-radius: 2px;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
}

.color-item:hover {
  transform: scale(1.1);
  border-color: #409eff;
}

.color-item-active {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.more-colors-section {
  margin-bottom: 12px;
  position: relative;
}

.more-colors-section .color-picker-section {
  position: absolute;
  left: 98%;
  top: 0;
  margin-left: 8px;
  margin-top: 0;
  z-index: 1000;
  background-color: var(--editor-color-white);
}

.more-colors-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  background-color: #fafafa;
}

.more-colors-button:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.more-colors-icon {
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.rainbow-circle {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: conic-gradient(
    from 0deg,
    #ff0000,
    #ff8000,
    #ffff00,
    #80ff00,
    #00ff00,
    #00ff80,
    #00ffff,
    #0080ff,
    #0000ff,
    #8000ff,
    #ff00ff,
    #ff0080,
    #ff0000
  );
}

.more-colors-button span {
  flex: 1;
  font-size: 12px;
  color: #606266;
}

.arrow-icon {
  color: #909399;
  font-size: 12px;
}

.recent-colors-section {
  margin-bottom: 12px;
}

.recent-colors-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 3px;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
  padding-top: 8px;
  border-top: 1px solid #ebeef5;
}

.default-color-button {
  width: 100%;
  padding: 6px 12px;
  border: 1px solid var(--editor-border-color);
  border-radius: var(--editor-radius);
  background: var(--editor-color-white);
  color: var(--editor-text-color);
  cursor: pointer;
  transition: all 0.2s;
  font-size: var(--editor-font-size);
  height: auto;
}

.default-color-button:hover {
  background: color-mix(in srgb, var(--editor-primary-color) 15%, transparent);
  border-color: var(--editor-primary-color);
  color: var(--editor-text-color);
}

.action-button {
  padding: 6px 12px;
  border: 1px solid var(--editor-border-color);
  border-radius: var(--editor-radius);
  font-size: var(--editor-font-size-small);
  cursor: pointer;
  transition: all 0.2s;
}

.action-button-text {
  background: transparent;
  color: var(--editor-text-color);
  border: none;
}

.action-button-text:hover {
  background: var(--editor-button-hover-background);
}

.action-button-primary {
  background: var(--editor-primary-color);
  color: var(--editor-color-white);
  border-color: var(--editor-primary-color);
}

.action-button-primary:hover {
  opacity: 0.9;
}
</style>
